<template>
  <div class="about">
    <!-- <h1>购物车</h1> -->
    <!-- <el-button type="danger" @click="remove">清空收藏夹</el-button> -->
    <div class="coll">
      <ul>
        <li v-for="(item, index) in list" :key="index">
          <input type="checkbox" checked class="j-checkbox" />
          <div class="shopname">{{ item.name }}</div>
          <div class="p-num">
            <div class="quantity-form">
              <span @click="reduce(index)">-</span>
              <input type="text" class="itxt" :value="item.quantity || 1" @input="updateQuantity(index, $event.target.value)" />
              <span @click="add(index)">+</span>
            </div>
          </div>
          <div class="price">{{ item.price }}</div>
          <div class="dele" @click="deleStore(index)">删除</div>
        </li>
      </ul>
    </div>
    <div>总价:{{ TotalPrice }}</div>
    <el-button type="primary" @click="checkout">结算</el-button>
  </div>
</template>

<script>
import { onMounted, ref, defineComponent, computed } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

export default defineComponent({
  setup() {
    let store = useStore()
    const router = useRouter()
    const list = ref([])

    onMounted(() => {
      val()
    })

    // 获取本地收藏
    const val = () => {
      list.value = JSON.parse(localStorage.getItem('Shop')) || []
      // 为每个商品添加 quantity 属性，默认值为 1
      list.value.forEach(item => {
        if (!item.quantity) {
          item.quantity = 1
        }
      })
    }

    const add = (index) => {
      list.value[index].quantity++
      localStorage.setItem('Shop', JSON.stringify(list.value))
    }

    const reduce = (index) => {
      if (list.value[index].quantity > 1) {
        list.value[index].quantity--
        localStorage.setItem('Shop', JSON.stringify(list.value))
      }
    }

    const updateQuantity = (index, value) => {
      const num = parseInt(value)
      if (!isNaN(num) && num > 0) {
        list.value[index].quantity = num
        localStorage.setItem('Shop', JSON.stringify(list.value))
      }
    }

    const deleStore = (index) => {
      list.value.splice(index, 1)
      localStorage.setItem('Shop', JSON.stringify(list.value))
    }

    const TotalPrice = computed(() => {
      return list.value.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0)
    })

    const checkout = () => {
      // 在这里可以添加结算逻辑，比如清空购物车等
      store.commit('remoColl')
      router.push({ name: 'success' })
    }

    return {
      list,
      add,
      reduce,
      deleStore,
      TotalPrice,
      checkout,
      updateQuantity
    }
  },
})
</script>

<style lang="less" scoped>
.about {
  h1 {
    text-align: center;
  }
  .coll {
    /* 可以添加样式 */
  }
}
</style>